#include "sys_config.h"

static int socket_fd = -1;
static int client_fd = -1;

static char recv_buf[256] = "";

bool Flag_Ok_Tcp = false;

/**
 * @brief 通过TCP发送给上位机
 * @note  套接字存放在全局变量socket_fd中
 * @param str   缓存区地址 
 * @param len   数据长度
 * @return  0发送成功 | 1服务器创建失败/客户端未连接   | -1发送失败
 */
int Tcp_Send_Buff(u8_t *str, u16_t len)
{
    int ret = -1;
    if(client_fd < 0)
        return 1;
    ret = send(client_fd, str, len, 0);
    if(ret < 0)
        return -1;
    return 0;
}

/**
 * @brief 初始化TCP服务器
 * @note 端口号SERVER_PORT定义在"sys_config.h"
 * @param {*}
 * @return {*}
 */
int TcpServer_Init(void)
{
    int result_code = 0; // 函数的返回值

    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(socket_fd < 0){
        printf("TcpServer_Init: socket create failed\n");
        return -1;
    }

    struct sockaddr_in local;
    local.sin_family = AF_INET;                           // IPV4
    local.sin_port = htons(SERVER_PORT);                     // 端口号
    local.sin_addr.s_addr = inet_addr(g_IP_Addr); // 使用本地IP地址进行创建TCP服务端

    printf("LocalIP = %s\n", g_IP_Addr);

    result_code = bind(socket_fd, (const struct sockaddr *)&local, sizeof(local));
    if(result_code < 0){
        printf("TcpServer_Init: bind failed\n");
        return -1;
    }

    result_code = listen(socket_fd, LISTEN_BACKLOG);
    if(result_code < 0){
        printf("listen failed\n");
        return -1;
    }
    return 0;
}


/**
 * @brief 接收请求、数据任务
 * @note 处理连接请求，接收数据，进行JSON解析后，存入全局变量globals_cmd_now; 发送对应指令给单片机
 * @param {*}
 * @return {*}
 */
void Tcp_Recv_Tack(void)
{
    while(1){
        struct sockaddr_in client;
        int client_len = sizeof(client);
        client_fd = accept(socket_fd, (const struct sockaddr *)&client, &client_len);
        if(client_fd < 0){
            sleep(1);
            printf("Tcp_Recv_Tack: accept failed or noclient\n\r");
            continue;
        }
        
        Flag_Ok_Tcp = true;
        printf("Tcp_Recv_Tack: connect success, accpet = %d\n\r", socket_fd);
        globals_car_status.client_number++;

        int ret = 0;
        while(1){
            memset(recv_buf, 0, sizeof(recv_buf));
            ret = recv(client_fd, recv_buf, sizeof(recv_buf), 0);
            if(ret <= 0){
                printf("Tcp_Recv_Tack: disconnect client\n");
                //oled_show("wait connect...", OLED_BUF_LEN, 1);
                globals_car_status.client_number--;
                Flag_Ok_Tcp = false;
                break;
            }

            printf("Tcp_Recv_Tack: recv_buf = %s\n", recv_buf);
            //memset(&globals_cmd_now, 0, sizeof(Cmd_Now));   //清空命令结构体更新最新命令
        	ret = 0;
            osMutexAcquire(globals_Mutex_ID, osWaitForever);
            ret = Json_Ana_RecvFromNet(recv_buf);
			switch (ret)
	        {
	        case 0:
	            globals_cmd_now.flag_cmd_update = 1;
	            globals_cmd_now.response = RESPONSE_SUCCESS;
	            break;
	        case 1:
	            globals_cmd_now.response = RESPONSE_ANA_FAILED;
	            break;
	        case 2:
	            globals_cmd_now.response = RESPONSE_UNDEFINE;
	            break;
	        default:
	            break;
	        }
            osMutexRelease(globals_Mutex_ID);
        }
    }
}


void Tcp_Send_Tack(void)
{
    int ret = -1;
    if(Flag_Ok_Tcp){
        //获取封装的json数据包
        char * json_data = Json_Enc_SendToNet();
        ret = send(client_fd,json_data,strlen(json_data),0);
        if(ret <= 0){
            printf("Tcp_Send_Tack send data error\n");
        }
        free(json_data);
        json_data = NULL;
    }
    sleep(1);


}
